<?php
/*
 * MySQLi Class
 * Written by Howard Liu <howard@ixnet.work>
 * Licensed under MIT
 */

namespace IXNetwork\Lib\Database\SQLDB;

use \Exception;

class MySQLi
{
    //Connection
    private $conn;

    //Result
    private $result;

    //Construction function; long means long connection
    public function __construct($dbHost, $dbUser, $dbPass, $dbName, $long = false)
    {
        $this->conn = $long?mysql_pconnect($dbHost, $dbUser, $dbPass):mysql_connect($dbHost, $dbUser, $dbPass);

        if (mysql_error()) {
            throw new Exception('An MySQLi connection error is thrown: '.$this->getError());
        }

        if ($this->getMysqlVersion() > '4.1') {
            mysql_query("SET NAMES 'utf8'");
        }

        if (!mysql_select_db($dbName, $this->conn)) {
            throw new Exception('An error incurred when selecting DB');
        }
        return $this->conn;
    }

    //Return current connection
    public function con()
    {
        return $this->conn;
    }

    //Close the connection
    public function close()
    {
        return $this->conn->close();
    }

    //Query
    public function query($query)
    {
        $this->result = @mysql_query($query);
        if (!$this->result) {
            throw new Exception('An MySQLi query error is thrown: '.$this->getError());
        } else {
            return $this->result;
        }
    }

    //Fetch Array
    public function fetchArray($result, $type = MYSQLI_ASSOC)
    {
        return mysql_fetch_array($result, $type);
    }

    //Query and Fetch Array
    public function xQuery($query)
    {
        $this->result = $this->query($query);
        return $this->fetchArray($this->result);
    }

    //Return number of rows
    public function numRows($result)
    {
        return mysql_num_rows($result);
    }

    //Get auto increment number
    public function insertId()
    {
        return mysql_insert_id();
    }

    //Get error information
    private function getError()
    {
        return '#' . $this->getErrNo() . ' - ' . mysql_error();
    }

    //Get error number
    private function getErrNo()
    {
        return mysql_errno();
    }

    //Get MySQL server version
    private function getMysqlVersion()
    {
        return mysql_get_server_info();
    }
}
